package com.globant;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

	private Pattern pattern;
	private Matcher matcher;
	UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public EmailValidator() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	/**
	 * Validates if email is not registered and of a valid format so that a new User can be created with this email address
	 * For this, it uses two methods: isRegistered() and isValid()
	 * 
	 * 
	 * @param String: email for validation
	 * @return true if it is not registered and valid format, false if it is register or invalid format
	 */	
	public boolean validate(final String email) {
		
	if (isAvailable(email)==false){
		return false;
	}else{
		if (isValid(email)==true){
			return true;
		}
	}return false;
	

	}

	
	/**
	 * Validates if email is registered in the data base
	 * 
	 * 
	 * @param String: email for validation
	 * @return true if it is not registered in the data base, false if it is
	 */	
	public boolean isAvailable(String email) {
					if(userDao.getUserByEmail(email)!=null){
		return false;
		}return true;
	}
	
	/**
	 * Validates if email is of a valid format and less than 200 characters

	 * 
	 * 
	 * @param String: email for validation
	 * @return true if it is valid, false if it is not
	 */	
	public boolean isValid(String email){
		 matcher = pattern.matcher(email);				 
		 if (matcher.matches() && email.length()<200){
		  return true;		
		 }else{
			 return false;
		 }
		  
	}
	
}
